package com.jplus.core.core;

import java.lang.annotation.Annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.core.AppConstant;
import com.jplus.core.bean.BeanHandle;
import com.jplus.core.bean.annotation.Component;
import com.jplus.core.util.ClassUtil;
import com.jplus.core.util.FormatUtil;

/**
 * jplus加载器
 * 
 * @author Yuanqy
 *
 */
public class CoreLoader {

    private static final Logger logger = LoggerFactory.getLogger(CoreLoader.class);

    public static void init() {
	ConfigHandle.init();
	AppConstant.CONFIG.refresh(ConfigHandle.getPropPath());
	for (Class<?> cla : AppConstant.APP_LOAD_HANDLE) {
	    logger.info("loadClass:{}", cla.getName());
	    ClassUtil.loadClass(cla.getName());
	}
	BeanHandle.clearCache();
	doInitMethod(Component.class);
	logger.info("=============== Jplus Is Loading Finish ~ o(*≧▽≦)ツ ~=============");
    }

    // =======================================================
    private static void doInitMethod(Class<? extends Annotation> cla) {
	try {
	    for (Class<?> cls : BeanHandle.beanAround) {
		if (cls.isAnnotationPresent(cla)) {
		    String initM = "";
		    if (cla.equals(Component.class))
			initM = ((Component) cls.getAnnotation(cla)).initMethod();
		    if (!FormatUtil.isEmpty(initM)) {
			Object obj = BeanHandle.getBean(cls);
			if (obj == null)
			    obj = cls.newInstance();
			cls.getMethod(initM, new Class<?>[] {}).invoke(obj, new Object[] {});
		    }
		}
	    }
	} catch (Exception e) {
	    logger.error("An exception occurs when the InitMethod do Invoke ", e);
	}
    }
}
